// // The Vue build version to load with the `import` command
// // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
// 引入element UI
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App';
// 引入路由
import router from './router';
// 引入状态管理
import store from './vuex/store';
import {
  Message
} from 'element-ui';

import axios from 'axios';
Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

// 使用element UI
Vue.use(ElementUI);
// 过滤器
import * as custom from './utils/util'

Object.keys(custom).forEach(key => {
  Vue.filter(key, custom[key])
})

Vue.prototype.$tableLoading=false;

import ECharts from 'vue-echarts'
import { use } from 'echarts/core'
// 手动引入 ECharts 各模块来减小打包体积

import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  BarChart
} from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent
} from 'echarts/components'

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  TooltipComponent
]);

// 全局注册组件（也可以使用局部注册）
Vue.component('v-chart', ECharts)

Vue.config.productionTip = false

var appAuthUrl = process.env.VUE_APP_AUTH_URL;
if(process.env.NODE_ENV === "production"){
  appAuthUrl = window.location.origin+appAuthUrl;
}

class OAuth2 {

  getToken(){
    let token=Vue.prototype.accessToken;
    if(!token){
      try{
      token=localStorage.getItem("access_token");
      }catch(err){
        Message({
          message: "cookie已被禁用，请开启cookie再重新打开",
          type: 'error'
        });
      }
      Vue.prototype.accessToken=token;
    }
    return token;
  }

  setToken(token){
    if(token){
      Vue.prototype.accessToken=token;
      localStorage.setItem("access_token",token);
    }
  }

  saveAuthData(data){
    this.setToken(data.access_token);
    localStorage.setItem("auth_data",JSON.stringify(data));
  }

  getAuthData(key){
    let data=localStorage.getItem("auth_data");
    if(data){
      data=JSON.parse(data);
    }
    if(key){
     return data[key];
    }
    return data;
  }
  getCookieToken() {
    const name="token";
    let token= document.cookie.match(`[;\\s+]?${name}=([^;]*)`)?.pop();
    if(token==sessionStorage.getItem("invalid_token")){
      return null;
    }
    return token;
  }
  removeToken(){
    const token=Vue.prototype.accessToken;
    Vue.prototype.accessToken="";
    localStorage.removeItem("access_token",token);
    sessionStorage.setItem("invalid_token",token);
  }
  /**
   * 使用code登录
   */
  codeLogin(callback){
    const arr=location.hash.split(/[&?]/);
    let code="";
    arr.forEach(kv=>{
      const keyVal=kv.split("=");
      if(keyVal[0]=="code"){
        code=keyVal[1];
      }
    })
    if(code){
      const token=this.getCookieToken();
      if(token && token!="undefined"){
        this.setToken(token);
        this.checkLogin(callback);
        return;
      }

      const authUrl=appAuthUrl;
      const clientId=process.env.VUE_APP_AUTH_CLIENTID;
      axios({
        method: "GET",
        url: `${authUrl}/codeLogin?code=${code}&clientId=${clientId}`,
      }).then(res => {
        if(res.status==200){
          const data=res.data;
          if(data.code==200){
            this.saveAuthData(data.data);
          }
        }
        this.checkLogin(callback);
      })
      .catch(err => {
        console.log(err);
        this.checkLogin(callback);
      });
    }else{
      this.checkLogin(callback);
    }
  }

  getLoginUri(){
  const authUrl=appAuthUrl;
  return `${authUrl}/authorize?response_type=code&client_id=iotkit&redirect_uri=${encodeURIComponent(location.href)}&scope=userinfo`
  }

  toLogin(){
    location.href=this.getLoginUri();
  }

  logout(){
    const authUrl=appAuthUrl;
    location.href=`${authUrl}/logout?accessToken=${this.getToken()}&redirect_uri=${encodeURIComponent(this.getLoginUri())}`;
  }

  replaceCode(url){
    return url.replace(/[&]?code=[^&]*/,"").replace("?&","?");
  }

  //登录检查
  checkLogin(callback){
    const authUrl=appAuthUrl;
    axios({
      method: "GET",
      url: authUrl + "/checkLogin",
    }).then(res => {
      console.log(JSON.stringify(res));
      if(res.status==200){
        let data=res.data;
        if(data.code==200){
          this.saveAuthData(data.data);
          callback();
          const url=location.href;
          let rawUrl=this.replaceCode(url);
          while(rawUrl.indexOf("code=")>=0){
            rawUrl=this.replaceCode(rawUrl);
          }
          if(rawUrl!=url){
            location.replace(rawUrl);
          }
          return;
        }
      }
      this.removeToken();
      this.toLogin();
    })
    .catch(err => {
      this.removeToken();
      console.log(err);
      callback();
    });
  }
}
const oauth2=new OAuth2();
Vue.prototype.oauth2=oauth2;

oauth2.codeLogin(()=>{
  return new Vue({
    el: '#app',
    router,
    store, //使用store vuex状态管理
    components: {
      App
    },
    template: '<App/>',
    data: {
      // 空的实例放到根组件下，所有的子组件都能调用
      Bus: new Vue()
    }
  });
});